/*
 * Copyright (c) 2021 The red-star Project
 *
 * Licensed under the Apache License, version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.inyourcode.example.service;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.Arrays;

/**
 * @author JackLei
 */
public class RedisScripter {
    DefaultRedisScript<Boolean> casScript;
    DefaultRedisScript<Long> idGenRedisScript;
    private RedisTemplate redisTemplate;

    public RedisScripter(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        casScript = new DefaultRedisScript<>();
        casScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("scripts/cas.lua")));
        casScript.setResultType(Boolean.class);

        idGenRedisScript = new DefaultRedisScript<>();
        idGenRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("scripts/idGen.lua")));
        idGenRedisScript.setResultType(Long.class);
    }

    public Object idGen(String key) {
        return redisTemplate.execute(idGenRedisScript, Arrays.asList(key));
    }

    public boolean cas(String key, String expect, String update) {
        Object execute = redisTemplate.execute(casScript, Arrays.asList(key), expect, update);

        if (execute == null) {
            return false;
        }

        return Boolean.valueOf(execute.toString());
    }
}
